package part05_原型模式.p03_深拷贝;

import java.io.*;

/**
 * @ClassName: DeepProtoType
 * @Author: AllenSun
 * @Date: 2019/12/6 21:26
 */
public class DeepProtoType implements Serializable,Cloneable {
    public String name;
    public DeepCloneableTarget deepCloneableTarget;
    //构造器
    public DeepProtoType(){
        super();
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        Object deep=null;
        deep=super.clone();
        DeepProtoType deepProtoType=(DeepProtoType) deep;
        deepProtoType.deepCloneableTarget=(DeepCloneableTarget) deepCloneableTarget.clone();
        return deepProtoType;
    }

    public Object deepClone(){
        ByteArrayOutputStream bos=null;
        ObjectOutputStream oos=null;
        ByteArrayInputStream bis=null;
        ObjectInputStream ois=null;

        try {
            bos=new ByteArrayOutputStream();
            oos=new ObjectOutputStream(bos);
            oos.writeObject(this);

            bis=new ByteArrayInputStream(bos.toByteArray());
            ois=new ObjectInputStream(bis);
            DeepProtoType copyObj=(DeepProtoType)ois.readObject();

            return copyObj;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                bos.close();
                oos.close();
                bis.close();
                ois.close();
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    }
}
















